/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ohosannotations.internal.core.handler;

import static com.helger.jcodemodel.JExpr.ref;

import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.TypeMirror;

import org.ohosannotations.OhosAnnotationsEnvironment;
import org.ohosannotations.ElementValidation;
import org.ohosannotations.annotations.ComponentById;
import org.ohosannotations.handler.BaseAnnotationHandler;
import org.ohosannotations.handler.MethodInjectionHandler;
import org.ohosannotations.helper.IdValidatorHelper;
import org.ohosannotations.helper.InjectHelper;
import org.ohosannotations.holder.EComponentWithViewSupportHolder;
import org.ohosannotations.holder.EFractionHolder;
import org.ohosannotations.holder.FoundViewHolder;
import org.ohosannotations.rclass.IRClass;

import com.helger.jcodemodel.AbstractJClass;
import com.helger.jcodemodel.IJAssignmentTarget;
import com.helger.jcodemodel.JBlock;
import com.helger.jcodemodel.JFieldRef;

/**
 * 组件通过id处理程序
 *
 * @author dev
 * @since 2021-07-22
 */
public class ComponentByIdHandler extends BaseAnnotationHandler<EComponentWithViewSupportHolder>
    implements MethodInjectionHandler<EComponentWithViewSupportHolder> {
    private final InjectHelper<EComponentWithViewSupportHolder> injectHelper;

    /**
     * 组件通过id处理程序
     *
     * @param environment 环境
     */
    public ComponentByIdHandler(OhosAnnotationsEnvironment environment) {
        super(ComponentById.class, environment);
        injectHelper = new InjectHelper<>(validatorHelper, this);
    }

    /**
     * 验证
     *
     * @param element 元素
     * @param validation 验证
     */
    @Override
    public void validate(Element element, ElementValidation validation) {
        injectHelper.validate(ComponentById.class, element, validation);
        if (!validation.isValid()) {
            return;
        }

        Element param = injectHelper.getParam(element);
        validatorHelper.isDeclaredType(param, validation);

        validatorHelper.extendsView(param, validation);

        validatorHelper.resIdsExist(element, IRClass.Res.ID,
            IdValidatorHelper.FallbackStrategy.USE_ELEMENT_NAME, validation);

        validatorHelper.isNotPrivate(element, validation);
    }

    /**
     * 过程
     *
     * @param element 元素
     * @param holder 持有人
     */
    @Override
    public void process(Element element, EComponentWithViewSupportHolder holder) {
        injectHelper.process(element, holder);
        if (holder instanceof EFractionHolder && isFieldInjection(element)) {
            String fieldName = element.getSimpleName().toString();
            ((EFractionHolder) holder).clearInjectedView(ref(fieldName));
        }
    }

    /**
     * 字段注入
     *
     * @param element 元素
     * @return boolean
     */
    private boolean isFieldInjection(Element element) {
        Element enclosingElement = element.getEnclosingElement();
        return !((element instanceof ExecutableElement) || (enclosingElement instanceof ExecutableElement));
    }

    /**
     * 得到调用块
     *
     * @param holder 持有人
     * @return {@link JBlock}
     */
    @Override
    public JBlock getInvocationBlock(EComponentWithViewSupportHolder holder) {
        return holder.getOnViewChangedBodyInjectionBlock();
    }

    /**
     * 赋值
     *
     * @param targetBlock 目标块
     * @param fieldRef 现场裁判
     * @param holder 持有人
     * @param element 元素
     * @param param 参数
     */
    @Override
    public void assignValue(JBlock targetBlock, IJAssignmentTarget fieldRef,
                            EComponentWithViewSupportHolder holder, Element element, Element param) {
        TypeMirror uiFieldTypeMirror = param.asType();
        JFieldRef idRef = annotationHelper.extractOneAnnotationFieldRef(element, IRClass.Res.ID, true);
        AbstractJClass viewClass = codeModelHelper.typeMirrorToJClass(uiFieldTypeMirror);

        IJAssignmentTarget viewHolderTarget = null;
        if (element.getKind() == ElementKind.FIELD) {
            viewHolderTarget = fieldRef;
        }
        FoundViewHolder viewHolder = holder.getFoundViewHolder(idRef, viewClass, viewHolderTarget);
        if (!viewHolder.getRef().equals(viewHolderTarget)) {
            targetBlock.add(fieldRef.assign(viewHolder.getOrCastRef(viewClass)));
        }
    }

    /**
     * 验证封装元素
     *
     * @param element 元素
     * @param valid 有效的
     */
    @Override
    public void validateEnclosingElement(Element element, ElementValidation valid) {
        validatorHelper.enclosingElementHasEnhancedViewSupportAnnotation(element, valid);
    }
}
